$(function(){

    // Main page slider
    if($.fn.glide)
    {
        $('.slider').glide({
            autoplay: 5000
        });
        $('.goods.list.top .slider').glide({
            autoplay: 10000
        });
    }

    GoodsList.init();
    ViewGoods.init();
    Search.init();
    TopMenu.init();
    CartList.init();


    if($.fn.lazyload)
    {
        $("img.lazy").lazyload();
        $("img.lazy").on('load', function(e){
            $(this).siblings('img.loader').remove();
        });
    }



});

var TopMenu = {
    init: function() {
        $('#top-menu menu li .sm').hover(function(e){
            $(this).parent().addClass('hover');
        }, function(e){
            $(this).parent().removeClass('hover');
        });
    }
};

var GoodsList = {
    init: function() {
        $('#filters > ul > li > ul li > a.disabled').on('click', function(e){e.preventDefault();});
    }
};

var ViewGoods = {
    init:  function() {
        var _fn_change = function(){
            var $id = $(this).val();

            AjaxLoader.show($(this).parent());

            $.post(window.location.href, {goods_id: $id}, function(response){
                AjaxLoader.hide();

                $('.goods.view').replaceWith(response);

                $('#select-color').on('change', _fn_change);

                ViewGoods.checkSizes();
                ViewGoods.initViewer();
                ViewGoods.initComments();
                ViewGoods.initCartButton();
                ViewGoods.initQuantityCheck();
            });
        }

        $('#select-color').on('change', _fn_change);

        ViewGoods.checkSizes();
        ViewGoods.initViewer();
        ViewGoods.initComments();
        ViewGoods.initSubscribe();
        ViewGoods.initCartButton();
        ViewGoods.initQuantityCheck();
    },

    checkSizes: function(){
        var $goodsId = $('#select-color').val();

        if(!$goodsId)
            return false;

        $.post('/goods/default/quantitycheck', {'goods_id': $goodsId}, function(response){
            if(response)
            {
                var data = {};
                try{
                    data = $.parseJSON(response);
                }
                catch($e){}

                if(data.success && data.counts)
                {
                    $('#select-size option').each(function(e){
                        var valueId = $(this).attr('value');
                        if(valueId !== '' && !data.counts[valueId])
                            $(this).remove();
                    });

                    if($('#select-size option').length == 1)
                        $('#select-size').replaceWith($('<div>Все размеры закончились</div>'))

                    ViewGoods.removeNoSizeWindow(response);
                }
                else
                {
                    $nsw = $('#no-size-window');

                    if($nsw.length)
                    {
                        $nsw.animate({top: '-1000px'}, 100, function(){
                            $nsw.remove();

                            ViewGoods.appendNoSizeWindow(response);
                        });
                    }

                    ViewGoods.appendNoSizeWindow(response);

                    if($('#select-size option').length == 1)
                        $('#select-size').replaceWith($('<div>Все размеры закончились</div>'))
                }
            }

        }, 'text');
    },

    initViewer: function() {
        if($.fn.fancybox)
        {
            $('.fancy').fancybox({
                live: false, openEffect: 'none', closeEffect: 'none',
                afterLoad : function(){
                    window.setTimeout(function(){
                        $('.fancybox-inner').zoom({'on' : 'grab'});
                    }, 1);
                }
            });

            $('.fancy-text').fancybox({type: 'ajax'});
        }

        if($.fn.zoom)
        {
            $('.zoom').zoom();
        }

        $('.goods.view .gallery .preview a').on('click', function(e){
            e.preventDefault();

            $(this).siblings('a').removeClass('selected');
            $(this).addClass('selected');

            if($(this).hasClass('video'))
            {
                var video = $(this).find('span.video-wrapper');
                $('.goods.view .gallery .zoom').hide().after(video.clone(true));
            }
            else
            {
                var url = $(this).attr('href');

                $('.goods.view .gallery .zoom img').attr('src', url);
                $('.goods.view .gallery .zoom').show().attr('href', url).siblings('span.video-wrapper').remove();
            }
        });
    },

    initCartButton: function() {
        $('.btn.buy:not(.in-cart)').on('click', function(e){
            e.preventDefault();

            var allowSubmit = true;
            var obj = $(this);
            var request = {};
            $('.cart-input').each(function(e){
                if($(this).val() == '' || $(this).find('option:selected').attr('rel') == '')
                {
                    $(this).css({borderColor: 'red'});
                    allowSubmit = false;
                }
                request[$(this).attr('name')] = $(this).val();
            });

            if(!allowSubmit)
                return false;

            $.get($(this).attr('href'), request, function(response){
                if(response && response.success)
                {
                    obj.replaceWith(response.btn);
                }
            }, 'json');
        });
    },

    initComments: function() {
        var comItems = $('.goods.view .comments .com-item');

        if(comItems.length > 0)
            $('#review-link').append($('<sup>('+ comItems.length +')</sup>'));
        else
            $('#review-link').text('Оставить отзыв'); //.attr('href', window.location.href +'#review')
    },

    initQuantityCheck: function() {
        $('#select-size').on('change', function(e){
            var $val = $(this).val();
            var $selectedOption = $(this).find('option:selected');
            var $stockValueId = $selectedOption.attr('rel');
            var $goodsId = $('#select-color').val();

            if(!$val)
                return false;

            AjaxLoader.show($(this).parent(), 'Проверка наличия ...');

            $.post('/goods/default/quantitycheck', {'goods_id': $goodsId, 'stock_value_id': $stockValueId}, function(response){
                AjaxLoader.hide();

                if(response)
                {
                    var data = {};
                    try{
                        data = $.parseJSON(response);
                    }
                    catch($e){}

                    if(data.success)
                    {
                        var text = $selectedOption.text().replace(' есть в наличии', '');
                        $selectedOption.text( text +' есть в наличии');

                        ViewGoods.removeNoSizeWindow(response);
                    }
                    else
                    {
                        $nsw = $('#no-size-window');

                        if($nsw.length)
                        {
                            $nsw.animate({top: '-1000px'}, 100, function(){
                                $nsw.remove();

                                ViewGoods.appendNoSizeWindow(response);
                            });
                        }

                        ViewGoods.appendNoSizeWindow(response);
                    }
                }

            }, 'text');
        });
    },

    appendNoSizeWindow: function(response) {
        var $gv = $('.goods.view');
        $gv.append(response);

        var $nsw = $('#no-size-window');
        $nsw.css({left: $gv.offset().left + 'px'});
        $nsw.animate({top: $gv.offset().top + 'px'}, 500, function(){
            $(this).find('input[type=email]').focus();
            $(this).find('>a').on('click', function(e){
                ViewGoods.removeNoSizeWindow();
            });
            ViewGoods.initSubscribe();
        });
    },
    removeNoSizeWindow: function(response) {
        response = response || '';

        $nsw = $('#no-size-window');

        if($nsw.length)
        {
            $nsw.animate({top: '-1000px'}, 100, function(){
                $nsw.remove();

                if(response)
                    ViewGoods.appendNoSizeWindow(response);
            });
        }
    },

    initSubscribe: function() {
        $('#subscribe-form, #bottom-subscribe-form').on('submit', function(e){
            e.preventDefault();

            var form = $(this);
            var request = $(this).serialize();

            AjaxLoader.show($(this));
            $.post($(this).attr('action'), request, function(response){
                AjaxLoader.hide();

                if(response.success)
                {
                    if(response.text)
                        form.find('.text').replaceWith(response.text);

                    if(response)
                        ViewGoods.removeNoSizeWindow();
                }
                else
                {
                    form.find('input').css({borderColor: '#d14836'});
                }
            }, 'json');

        });
    }
};

var CartList = {
    init: function() {
        $('.cart.list table td.quantity').on('blur', 'input', function(){
            $(this).parents('form').submit();
        });
    }
};

var Search = {
    timer: null,
    init : function() {
        $('#search input[name=q]').on('keyup focus', function(e){

            var matchedWindow = null, selected = null;

            if(Search.timer !== null)
                clearTimeout(Search.timer);

            if(e.keyCode == '40')
            {
                matchedWindow = $('#search .matched');

                selected = matchedWindow.find('div.selected');
                if(selected.length > 0)
                    selected = selected.next();

                if(selected.length == 0)
                    selected = matchedWindow.find('div').first();

                matchedWindow.find('div').removeClass('selected');
                selected.addClass('selected');
                Search.setTextToInput(selected.text());

                return false;
            }
            else if(e.keyCode == '38')
            {
                matchedWindow = $('#search .matched');

                selected = matchedWindow.find('div.selected');
                if(selected.length > 0)
                    selected = selected.prev();

                if(selected.length == 0)
                    selected = matchedWindow.find('div').last();

                matchedWindow.find('div').removeClass('selected');
                selected.addClass('selected');
                Search.setTextToInput(selected.text());

                return false;
            }
            else if(e.keyCode == '13')
            {
                if($('#search .matched div.selected').text())
                {
                    Search.setTextToInput($('#search .matched div.selected').text());
                }

                $('#search form').submit();

                return false;
            }
            else if(e.keyCode == '32')
                return true;

            var input = $(this);
            var q = input.val();

            if(q.length < 2 || q.match(/[a-zA-Z0-9]*/i) === false)
            {
                $('#search .matched').remove();
                return true;
            }

            Search.timer = window.setTimeout(function(){
                AjaxLoader.show($('#search button'));
                $.get(input.parents('form').attr('action'), {'q': q}, function(response){
                    AjaxLoader.hide();
                    $('#search .matched').remove();
                    if(response && response.count > 0)
                    {
                        var html = Search.buildWindow(response.matched, q);
                        input.after($(html));
                    }
                }, 'json');
            }, 500);
        });

        $('#search').on('click', '.matched div', function(){
            $('#search input[name=q]').val($(this).text());
            $('#search form').submit();
        });

        $('#search input[name=q]').on('blur', function(){
            window.setTimeout(function(){
                $('#search .matched').remove();
            }, 100);
        });
    },

    setTextToInput : function(text){
        $('#search input[name=q]').val(text);
    },

    buildWindow : function(items, q){
        var html = '<div class="matched">';

        for(var i in items)
        {
//            var words = q.split(' ');
            var item = items[i];

//            for(var iw in words)
//            {
//                item = item.replace(new RegExp("("+words[iw]+")", "gi"), "<b>$1</b>");
//            }
            html += '<div>'+ item +'</div>';
        }

        html += '</div>';

        return html;
    }
};

var AjaxLoader = {
    show : function( obj, text )
    {
        text = text || '';
        obj = $(obj);

        var _loader = AjaxLoader._setLayers( obj, text );

        $('body div:first').after(_loader);
    },
    _setLayers : function( obj, text )
    {
        $(obj).each(function(){

            var _position = $(this).position();

            var _box = $('<div />', {
                'class' : 'ajax-loader'+ (text != '' ? ' text' : '')
            }).css({
                    'width' : $(this).innerWidth(),
                    'height' : $(this).innerHeight(),
                    'left'	: 0,
                    'top'	: 0
                });

            if(text != '')
            {
                _box.append($('<p>'+ text +'</p>'));
            }

            _box.append($('<img />', {
                'src' : ''
            }));

            $(this).css({
                'position': 'relative'
            }).append( _box );
        });
    },
    hide : function()
    {
        $('.ajax-loader').hide(1).remove();
    }
};

$(function(){
    $.fn.myPreviewSlider = function() {

        $(this).css({position: 'relative', overflow: 'hidden'});

        var maxWidth = $(this).innerWidth();
        var totalWidth = 0;
        var childs = $(this).children('.item');
        var childWidth = 0;
        var totalCount = 0;
        var countVisible = 0;
        childs.each(function(e){
            if($(this)[0].clientWidth > 0)
            {
                totalWidth += $(this)[0].clientWidth;
                childWidth = $(this)[0].clientWidth;
                totalCount++;
            }

            if((countVisible * childWidth) < maxWidth)
                countVisible++;
        });

        var slide = $('<div />').css({
            width: totalWidth+'px',
            position: 'absolute',
            left: '0',
            top: '0'
        });

        var sliderWrapper = $('<div />').addClass('slider-wrapper');

        $(this).append(sliderWrapper.append(slide.append(childs)));

        var width = 0;
        sliderWrapper.after($('<a href="jsvascript: return void(0);"></a>').addClass('arr right').css({
            position: 'absolute', zIndex: 2, right: '0', top: '50%', width: '31px', height: '75px', margin: '-37px 0 0 0', padding: '0',
            background: 'url(/img/arrow-lr.png) no-repeat right center'
        }).on('click', function(e){
                e.preventDefault();

                var countHidden = width / childWidth;
                width = totalCount - (countVisible + countHidden) >= countVisible ? (countVisible + countHidden) * childWidth : (totalCount - countVisible) * childWidth;
                slide.stop().animate({left: '-'+ width +'px'}, 100);
            }));

        sliderWrapper.before($('<a href="jsvascript: return void(0);"></a>').addClass('arr left').css({
            position: 'absolute', zIndex: 2, left: '0', top: '50%', width: '31px', height: '75px', margin: '-37px 0 0 0', padding: '0',
            background: 'url(/img/arrow-lr.png) no-repeat left center'
        }).on('click', function(e){
                e.preventDefault();

                var countHidden = width / childWidth;
                width = countHidden >= countVisible ? width - countVisible * childWidth : width - countHidden * childWidth;
                slide.stop().animate({left: '-'+ width +'px'}, 100);
            }));
    };


    $('.my-slider').myPreviewSlider();
});